//index.js
const app = getApp()
import util from '../../util/index.js'
Page({
  data: {
    isShowLogin: false, //是否需要登录
    isEntered: false, //是否需要完善资料
    tab: 1,
    isShwoData: false, //是否显示数据,
    data: [],
  },

  onLoad: function () {

  },
  toLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  tabChange({
    target: {
      dataset: {
        index
      }
    }
  }) {
    index = parseInt(index);
    this.setData({
      tab: index
    })
    this.data.tab = index;
    this.getData();
  },
  book({
    currentTarget: {
      dataset: {
        id
      }
    }
  }) {
    // const route = this.data.data.find(item=>item._id == id)
    wx.navigateTo({
      url: '/pages/appointment/appointment?id=' + id,
    })
    // this.selectComponent('#appointment').show(id, this.data.tab, route.stations);
  },
  toDetail({
    currentTarget: {
      dataset: {
        id
      }
    }
  }) {
    wx.navigateTo({
      url: '/pages/routeDetail/routeDetail?c=1&id=' + id,
    })
  },
  toImprove() {
    wx.navigateTo({
      url: '/pages/improve/improve',
    })
  },
  getData() {
    wx.showLoading({
      title: '加载中...',
    })
    util.ajax("route", {
      data: {
        action: "list",
        type: this.data.tab
      }
    }).then(({
      code,
      data,
      msg
    }) => {
      wx.hideLoading()
      let routeId = wx.getStorageSync("routeId");
      //判断是否有缓存的路线 用于展示在第一条数据
      if (routeId) {
        const id = routeId[this.data.tab];
        if (id) {
          data.some((item, index) => {
            if (item._id == id) {
              data.splice(index, 1);
              data = [item, ...data]
              return true;
            }
          })
        }

      }

      if (code == 1) {
        this.setData({
          data,
          isShwoData: true,
        })
      } else {
        util.tip(msg)
      }
    }, wx.hideLoading);
  },
  onShow() {
    //已获取数据 不再刷新数据
    if (this.data.isShwoData) {
      this.getData();
      return;
    }
    //校验权限
    util.ajax("user", {
      data: {
        action: "loginByOpenid"
      }
    }).then(({
      code,
      msg,
      data
    }) => {
      if (code == 1) { //正常用户
        wx.setStorageSync("user", data)
        this.setData({
          isShowLogin: false,
          isEntered: false,
        })
        this.getData();
      } else if (code == -3) { //未完善信息
        this.setData({
          isShowLogin: false,
          isEntered: true,
        })
      } else if (code == -1) { //未登录
        this.setData({
          isShowLogin: true,
        })
      } else { //帐号被锁定 
        wx.showModal({
          title: '提示',
          content: msg,
          showCancel: false,
          confirmText: "知道了"
        })
      }
    })
  },
  onShareAppMessage() {
    return {
      title: "预约班车",
      imageUrl: '/images/share.png',
    }
  },
  onShareTimeline() {
    return {
      title: "预约班车",
      imageUrl: '/images/share.png',
    }
  }

})